# select testFormNumber as '委托单号',sampleModel as '样品型号',sampleNumber as '样品编号',testFormItemName as '委托项名称',
# equipmentName as '设备名称',equipmentNumber as '设备编号',equipmentTWName as '设备台位名称',testCondition as '检测条件',
# varStr1 as '电流',varStr3 as '排气压力',varStr5 as '吸气压力',varStr7 as '排气温度',varStr9 as '吸气温度',varStr11 as '壳体温度',varStr13 as '频率'
# from actualtestvalueg3 where equipmentNumber = 'TA2211080005160024010101' and testFormNumber = 'ST2024099386' and sampleNumber = '2409060741K';

import os

class SqlQueryBuilder:
    def __init__(self, tbl, cons, fields):
        self.tbl = tbl
        self.cons = cons
        self.fields = fields

    def construct_sql(self):
        # 构造 SELECT 部分
        select_part = ", ".join(self.fields)
        
        # 构造 WHERE 条件
        conditions = []
        for key, value in self.cons.items():
            conditions.append(f"{key} = '{value}'")
        
        # 拼接 SQL 查询
        sql = f"SELECT {select_part} FROM {self.tbl} WHERE {' AND '.join(conditions)};"
        return sql

    def write_to_file(self, file_path):
        sql_query = self.construct_sql()
        with open(file_path, 'a') as file:
            file.write(sql_query + '\n')
        print(f"SQL 语句已成功写入到 {file_path}")

# 示例表名
tbl = 'actualtestvalueg3'

# 示例查询条件
cons = {
    'testFormNumber': 'ST2024099386',
    'sampleNumber': '2409060741K',
    'equipmentNumber': 'TA2211080005160024010101'
}

# 示例字段列表
fields = [
    "testFormNumber as '委托单号'",
    "sampleModel as '样品型号'",
    "sampleNumber as '样品编号'",
    "testFormItemName as '委托项名称'",
    "equipmentName as '设备名称'",
    "equipmentNumber as '设备编号'",
    "equipmentTWName as '设备台位名称'",
    "testCondition as '检测条件'",
    "varStr1 as '电流'",
    "varStr3 as '排气压力'",
    "varStr5 as '吸气压力'",
    "varStr7 as '排气温度'",
    "varStr9 as '吸气温度'",
    "varStr11 as '壳体温度'",
    "varStr13 as '频率'"
]

# 创建 SqlQueryBuilder 实例
builder = SqlQueryBuilder(tbl, cons, fields)

# 构造 SQL 语句并打印
sql_query = builder.construct_sql()
print(sql_query)

# 获取当前文件所在的目录
current_directory = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(current_directory, 'sql_query.txt')

# 将 SQL 语句写入文件
builder.write_to_file(file_path)